package com.julang.check.controller.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.jpay.alipay.AliPayApi;
import com.jpay.alipay.AliPayApiConfig;
import com.jpay.vo.AjaxResult;
import com.julang.check.bean.User;
import com.julang.check.bean.pay.AliPayBean;
import com.julang.check.bean.pay.PayData;
import com.julang.check.api.mapper.UserMapper;
import com.julang.check.utils.CommonData;
import com.julang.check.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.julang.check.utils.CommonData.ONEOFNUMBER;
import static com.julang.check.utils.CommonData.SUCCESS;

import java.util.HashMap;
import java.util.Map;
/**
 * @author 赵自强
 * */
@Controller
@RequestMapping("/api/alipay")
public class AbstractAliPayController extends AbstractAliPayApiController {
    private static final Logger log = LoggerFactory.getLogger(AbstractAliPayController.class);

	@Autowired
	private AliPayBean aliPayBean;
	@Resource
	private UserMapper userMapper;
	private AjaxResult result = new AjaxResult();

	@Override
	public AliPayApiConfig getApiConfig() {
		return AliPayApiConfig.New()
				.setAppId(aliPayBean.getAppId())
				.setAlipayPublicKey(aliPayBean.getPublicKey())
				.setCharset("UTF-8")
				.setPrivateKey(aliPayBean.getPrivateKey())
				.setServiceUrl(aliPayBean.getServerUrl())
				.setSignType("RSA2")
				.build();
	}

	/**
	 * 扫码支付
	 */
	@RequestMapping(value = "/tradePrecreatePay")
	@ResponseBody
	public Result<String> tradePrecreatePay(@RequestParam("total_fee") String totalFee, HttpServletRequest request) {
		Result result = new Result();
		String userId = getUserId();
		if (PayData.haveUnusedOrderByUserId(userId)) {
			result.fail(CommonData.FAIL, "存在未支付的账单", "");
			return result;
		}
		String subject = "PaperKey论文服务积分充值";
		String storeId = "123";
		String notifyUrl = aliPayBean.getDomain() + "/api/alipay/notify_url";
		String order = String.valueOf(System.currentTimeMillis());
		AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
		model.setSubject(subject);
		model.setTotalAmount(totalFee);
		model.setStoreId(storeId);
		model.setTimeoutExpress("90m");
		model.setOutTradeNo(order);
		try {
			String resultStr = AliPayApi.tradePrecreatePayToResponse(model, notifyUrl).getBody();
			JSONObject jsonObject = JSONObject.parseObject(resultStr);
			String qrCodeUrl = jsonObject.getJSONObject("alipay_trade_precreate_response").getString("qr_code");
			PayData.createNewOrder(userId, order, totalFee, qrCodeUrl, 0);
			result.setCode(SUCCESS);
			result.setMessage(qrCodeUrl);
			result.setData(order);
			result.setResult(true);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.setCode(CommonData.FAIL);
		return result;
	}

	@RequestMapping(value = "/return_url")
	@ResponseBody
	public String returnUrl(HttpServletRequest request) {
		try {
			// 获取支付宝GET过来反馈信息
			Map<String, String> map = AliPayApi.toMap(request);
			for (Map.Entry<String, String> entry : map.entrySet()) {
				System.out.println(entry.getKey() + " = " + entry.getValue());
			}

			boolean verifyResult = AlipaySignature.rsaCheckV1(map, aliPayBean.getPublicKey(), "UTF-8",
					"RSA2");
			if (verifyResult) {
				// 验证成功
				System.out.println("return_url 验证成功");
				return "success";
			} else {
				System.out.println("return_url 验证失败");
				return "failure";
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			return "failure";
		}
	}



	@RequestMapping(value = "/notify_url")
	@ResponseBody
	public String  notifyUrl(HttpServletRequest request) {
		try {
			// 获取支付宝POST过来反馈信息
			Map<String, String> params = AliPayApi.toMap(request);
			System.out.println("收到支付通知");
			for (Map.Entry<String, String> entry : params.entrySet()) {
				System.out.println(entry.getKey() + " = " + entry.getValue());
			}

			boolean verifyResult = AlipaySignature.rsaCheckV1(params, aliPayBean.getPublicKey(), "UTF-8",
					"RSA2");

			if (verifyResult) {
				// 验证成功
				System.out.println("notify_url 验证成功succcess");
				String userId = PayData.getUserIdByOrderId(params.get("out_trade_no"));
				if ( userId != null) {
					User user = userMapper.selectById(userId);
					float m = PayData.getMoneyByOrderId(params.get("out_trade_no"));
					if (m != -1) {
						user.setJifen(user.getJifen() + m);
						userMapper.updateById(user);
						System.out.println("支付宝： 更新数据库表积分选项");
					}else {
						System.out.println("支付宝： 表中没有相关订单数据");
					}
				}else {
					System.out.println("支付宝： 找不到UserID");
				}
				PayData.makeOrderFinished(params.get("out_trade_no"), ONEOFNUMBER, params.get("trade_no"),
						params.get("buyer_logon_id"));
				return "success";
			} else {
				System.out.println("notify_url 验证失败");
				// TODO
				return "failure";
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			return "failure";
		}
	}
}
